//
//  UIDevice+HHAuthHelper.m
//  Pods
//
//  Created by Basic on 2017/8/16.
//
//

#import "UIDevice+HHAuthHelper.h"
#import <AVFoundation/AVMediaFormat.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/PHPhotoLibrary.h>

#import <BCUIKit/UIAlertController+BCHelper.h>
#import <BCFoundation/BCFoundationUtils.h>
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
#import <UserNotifications/UserNotifications.h>
#endif


@implementation UIDevice (HHAuthHelper)

#pragma mark - 通讯录权限

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ (ABAuthorizationStatus )hh_addressbookAuth
{
    ABAuthorizationStatus authState = ABAddressBookGetAuthorizationStatus();
    return authState;
}
+ (void)hh_useAddressbook:(void(^)(BOOL support, BOOL authorized) )openBlock
{
    //判断用户授权状态
    ABAuthorizationStatus state = ABAddressBookGetAuthorizationStatus();
    switch (state) {
        case kABAuthorizationStatusNotDetermined:
        {
            ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
            //2.请求授权 (用户决定后就会回调block)
            ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                dispatch_main_async_bcsafe(^{
                    if(openBlock){
                        openBlock(YES,granted);
                    }
                });
            });
        }
            break;
        case kABAuthorizationStatusRestricted:
        case kABAuthorizationStatusDenied://拒绝
        {
            NSURL *settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            NSString *appName = [[NSBundle mainBundle] infoDictionary][@"CFBundleDisplayName"];
            BOOL canOpenSetting = [[UIApplication sharedApplication] canOpenURL:settingUrl];
            if (canOpenSetting) {
                //可以打开设置
                NSString *message = [NSString stringWithFormat:@"请在\"设置\"中允许“%@” APP 访问你的通讯录", appName];
                [UIAlertController bc_showAlert:message message:nil actionBlock:^(NSInteger bottonIndex) {
                    if(bottonIndex>0){
                        [[UIApplication sharedApplication] openURL:settingUrl];
                    }
                } cancelButtonTitle:BCLOC(@"取消") otherButtonTitles:BCLOC(@"去设置"),nil];
            }
            else{
                //不可以打开设置
                NSString *message = [NSString stringWithFormat:@"请在 iPhone 的[设置]-[隐私]-[通讯录]选项中，允许“%@” APP 访问你的通讯录", appName];
                [UIAlertController bc_showAlert:message message:nil actionBlock:nil cancelButtonTitle:BCLOC(@"知道了") otherButtonTitles:nil];
            }
            if(openBlock){
                openBlock(YES, NO);
            }
        }
            break;
        case kABAuthorizationStatusAuthorized://允许
        {
            if(openBlock){
                openBlock(YES, YES);
            }
        }
            break;
        default:
        {
            if(openBlock){
                openBlock(YES, NO);
            }
        }
            break;
    }
}

#pragma clang diagnostic pop

+ (void)hh_useMicrophone:(void(^)(BOOL support, BOOL authorized) )openBlock
{
    AVAudioSessionRecordPermission status = [[AVAudioSession sharedInstance] recordPermission];
    switch (status) {
        case AVAudioSessionRecordPermissionUndetermined://未决定状态
        {
            [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
                dispatch_main_async_bcsafe(^{
                    if(openBlock){
                        openBlock(YES,granted);
                    }
                });
            }];
        }
            break;
        case AVAudioSessionRecordPermissionGranted://已经取得权限
        {
            if(openBlock){
                openBlock(YES, YES);
            }
            break;
        }
        case AVAudioSessionRecordPermissionDenied://拒绝
        {
            NSURL *settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            NSString *appName = [[NSBundle mainBundle] infoDictionary][@"CFBundleDisplayName"];
            BOOL canOpenSetting = [[UIApplication sharedApplication] canOpenURL:settingUrl];
            if (canOpenSetting) {
                //可以打开设置
                NSString *message = [NSString stringWithFormat:@"请在\"设置\"中允许“%@” APP 访问你的麦克风", appName];
                [UIAlertController bc_showAlert:message message:nil actionBlock:^(NSInteger bottonIndex) {
                    if(bottonIndex>0){
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
    NSDictionary<UIApplicationOpenExternalURLOptionsKey, id> *options = [[NSDictionary<UIApplicationOpenExternalURLOptionsKey, id> alloc] init];
    [[UIApplication sharedApplication] openURL:settingUrl options:options completionHandler:nil];
#else
    [[UIApplication sharedApplication] openURL:settingUrl];
#endif
                    }
                } cancelButtonTitle:BCLOC(@"取消") otherButtonTitles:BCLOC(@"去设置"),nil];
            }
            else{
                //不可以打开设置
                NSString *message = [NSString stringWithFormat:@"请在 iPhone 的[设置]-[隐私]-[麦克风]选项中，允许“%@” APP 访问你的麦克风", appName];
                [UIAlertController bc_showAlert:message message:nil actionBlock:nil cancelButtonTitle:BCLOC(@"知道了") otherButtonTitles:nil];
            }
            if(openBlock){
                openBlock(YES, NO);
            }
        }
        default:
        {
            if(openBlock){
                openBlock(YES, NO);
            }
        }
            break;
    }
}

#pragma mark - 相册、拍照权限
+ (void)hh_useCamera:(void(^)(BOOL support, BOOL authorized) )openBlock
{
    if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        //设备不支持拍照
        if(openBlock){
            openBlock(NO,NO);
        }
        return ;
    }
    //判断权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    switch (authStatus) {
            //未决定状态
        case AVAuthorizationStatusNotDetermined:
        {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                dispatch_main_async_bcsafe(^{
                    if(openBlock){
                        openBlock(YES,granted);
                    }
                });
            }];
        }
            break;
        case AVAuthorizationStatusRestricted:
        case AVAuthorizationStatusDenied:
        {
            //被拒绝
            NSURL *settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
            NSString *appName = [infoDict valueForKey:@"CFBundleDisplayName"];
            if (!appName) appName = [infoDict valueForKey:@"CFBundleName"];
            if (!appName) appName = [infoDict valueForKey:@"CFBundleExecutable"];
            BOOL canOpenSetting = [[UIApplication sharedApplication] canOpenURL:settingUrl];
            if (canOpenSetting) {
                //可以打开设置
                NSString *message = [NSString stringWithFormat:@"请在设置中允许“%@” APP 访问你的相机", appName];
                [UIAlertController bc_showAlert:message message:nil actionBlock:^(NSInteger bottonIndex) {
                    if(bottonIndex>0){
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
    NSDictionary<UIApplicationOpenExternalURLOptionsKey, id> *options = [[NSDictionary<UIApplicationOpenExternalURLOptionsKey, id> alloc] init];
    [[UIApplication sharedApplication] openURL:settingUrl options:options completionHandler:nil];
#else
    [[UIApplication sharedApplication] openURL:settingUrl];
#endif
                    }
                } cancelButtonTitle:BCLOC(@"取消") otherButtonTitles:BCLOC(@"设置"),nil];
            }
            else{
                //不可以打开设置
                NSString *message = [NSString stringWithFormat:@"请在 iPhone 的[设置]-[隐私]-[相机]选项中，允许“%@” APP 访问你的相机", appName];
                [UIAlertController bc_showAlert:message message:nil actionBlock:nil cancelButtonTitle:BCLOC(@"知道了") otherButtonTitles:nil];
            }
            if(openBlock){
                openBlock(YES, NO);
            }
        }
            break;
        case AVAuthorizationStatusAuthorized:
        {
            //已经授权
            if(openBlock){
                openBlock(YES, YES);
            }
        }
            break;
        default:
        {
            if(openBlock){
                openBlock(YES, NO);
            }
        }
            break;
    }
}


+ (void)hh_usePhoto:(void(^)(BOOL support, BOOL authorized, BOOL selectedCancel) )openBlock
{
    //判断权限
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    switch (status) {
        case PHAuthorizationStatusNotDetermined://未决定
        {
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
                    dispatch_main_async_bcsafe(^{
                        if(openBlock){
                            openBlock(YES, NO, NO);
                        }
                    });
                    
                }
                else{
                    dispatch_main_async_bcsafe(^{
                        if(openBlock){
                            openBlock(YES,YES, NO);
                        }
                    });
                }
            }];
        }
            break;
        case PHAuthorizationStatusRestricted:
        case PHAuthorizationStatusDenied://被拒绝
        {
            NSURL *settingUrl = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            BOOL canOpenSetting = [[UIApplication sharedApplication] canOpenURL:settingUrl];
            NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
            NSString *appName = [infoDict valueForKey:@"CFBundleDisplayName"];
            if (!appName) appName = [infoDict valueForKey:@"CFBundleName"];
            if (!appName) appName = [infoDict valueForKey:@"CFBundleExecutable"];
            if (canOpenSetting) {
                //可以打开设置
                NSString *message = [NSString stringWithFormat:@"请在设置中允许“%@” APP 访问你的照片", appName];
                [UIAlertController bc_showAlert:message message:nil actionBlock:^(NSInteger bottonIndex) {
                    if(bottonIndex>0){
    #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
        NSDictionary<UIApplicationOpenExternalURLOptionsKey, id> *options = [[NSDictionary<UIApplicationOpenExternalURLOptionsKey, id> alloc] init];
        [[UIApplication sharedApplication] openURL:settingUrl options:options completionHandler:nil];
    #else
        [[UIApplication sharedApplication] openURL:settingUrl];
    #endif
                    }
                } cancelButtonTitle:BCLOC(@"取消") otherButtonTitles:BCLOC(@"设置"),nil];
            }
            else{
                //不可以打开设置
                NSString *message = [NSString stringWithFormat:@"请在 iPhone 的[设置]-[隐私]-[照片]选项中，允许“%@” APP 访问你的照片", appName];
                [UIAlertController bc_showAlert:message message:nil actionBlock:^(NSInteger bottonIndex) {
                    if (openBlock) {
                        openBlock(NO, NO, YES);
                    }
                } cancelButtonTitle:BCLOC(@"知道了") otherButtonTitles:nil];
            }
            if(openBlock){
                openBlock(YES, NO, NO);
            }
        }
            break;
            
        case PHAuthorizationStatusAuthorized://已经授权过
        {
            if(openBlock){
                openBlock(YES, YES, NO);
            }
        }
            break;
        default:
        {
            if(openBlock){
                openBlock(YES, NO, NO);
            }
        }
            break;
    }
}

+ (void)hh_useNotification:(void (^)(BOOL authorized) )openBlock {
    //ios 10
    void(^ios10Block)(void) = ^(void){
        if (@available(iOS 10.0, *)) {
            [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                BOOL auth = (settings.authorizationStatus == UNAuthorizationStatusAuthorized);
                dispatch_main_async_bcsafe(^{
                    if (openBlock) {
                        openBlock(auth);
                    }
                });
            }];
        }
    };
    if (@available(iOS 10.0, *)) {
        ios10Block();
    }
    else {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000
        ios10Block();
#else
        BOOL noAuth = ([[UIApplication sharedApplication] currentUserNotificationSettings].types  == UIUserNotificationTypeNone);
        dispatch_main_async_bcsafe(^{
            if (openBlock) {
                openBlock(!noAuth);
            }
        });
#endif
    }
}
@end
